﻿using Microsoft.SqlServer.Types;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Linq;
using System.Web;

namespace SqlSugar_Geometry_Model
{
    public class LineConverter : ISugarDataConverter
    {
        public SugarParameter ParameterConverter<T>(Object value, int i)
        {
            var name = "@mylocationp" + i;
            var line = value as Line;
            var wkt = line != null ? $"{line.ToString()}" : null;
            Debug.WriteLine("wkt is :" + wkt);
            // 设置Value为SqlGeometry类型
            SqlGeometry geometry = null;
            if (line != null)
            {
                // 创建一个SqlGeometry对象（这里使用WKT表示的线）  
                geometry = SqlGeometry.Parse(new SqlString(wkt));
                geometry.STSrid = 4490;
                geometry.MakeValid(); // MakeValid确保几何体是有效的  
            }
            var parameter = new SugarParameter(name, geometry)
            {
                UdtTypeName = "geometry",
                CustomDbType = System.Data.SqlDbType.Udt,
            };

            return parameter;
        }

        public T QueryConverter<T>(IDataRecord dr, int i)
        {
            var str = dr.GetValue(i).ToString();
            if (string.IsNullOrWhiteSpace(str))
            {
              return default;
            }
            
            var partstr = str.Replace("LINESTRING (", "").Replace(")", "");
            var parts = partstr.Split(',');
            var poits = new Location[parts.Length];
            var line = new Line(poits);
            var poitstr = parts[0].Split(' ');
            if (poitstr.Length == 3 &&
            double.TryParse(poitstr[0], out var x) &&
            double.TryParse(poitstr[1], out var y) &&
            double.TryParse(poitstr[2], out var z))
            {
                poits[0] = new Location(x, y, z);
            }
            for (int a = 1; a < parts.Length; a++)
            {
                var poitstr1 = parts[a].Split(' ');
                if (poitstr1.Length == 4 &&
                double.TryParse(poitstr1[1], out var _x) &&
                double.TryParse(poitstr1[2], out var _y) &&
                double.TryParse(poitstr1[3], out var _z))
                {
                    poits[a] = new Location(_x, _y, _z);
                }
            }
            return (T)(object)line;
        }
    }
}